package com.hsmpay.mobile.action.account.scanCodePay;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.common.util.OrderTypeUtil;
import com.hsmpay.common.util.system.Constant;
import com.hsmpay.mobile.pojo.bank.Bank;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.pojo.trans.TransPriorSettle;
import com.hsmpay.mobile.pojo.user.UserMoney;
import com.hsmpay.mobile.service.account.AccountManageQ4Service;
import com.hsmpay.mobile.service.account.CashMoneyService;
import com.hsmpay.mobile.service.bank.BankService;
import com.hsmpay.mobile.service.trans.Qian4SendLogService;
import com.hsmpay.mobile.service.trans.TransOrderService;
import com.hsmpay.mobile.service.trans.TransPriorSettleService;
import com.hsmpay.mobile.service.trans.TransRefuseCardService;
import com.hsmpay.mobile.service.user.UserMoneyService;
import com.hsmpay.mobile.service.user.UserTransLimitService;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.service.ds.JQScanCodePayService;
import com.hsmpay.qian4.service.ds.XYScanCodePayService;
import com.hsmpay.qian4.service.ds.impl.XYScanCodePayServiceImpl;
import com.hsmpay.tencent.common.XMLParser;
import com.hsmpay.utils.JSONUtil;
import com.hsmpay.utils.system.ConConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 扫码支付业务
 */
@Controller("scanCodePayAction")
@Scope("prototype")
public class ScanCodePayAction extends ScanCodePayBaseAction {

    private static final long serialVersionUID = 7459445231353195197L;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    public static final String Certificate = Constant.getAttribute("CERTIFICATE_BASE_URL") + "c.action?d=";//小票 base路径

    @Resource(name = "userTransLimitService")
    private UserTransLimitService<BasePojo, Long> userTransLimitService;
    @Resource(name = "transRefuseCardService")
    protected TransRefuseCardService<BasePojo, Long> transRefuseCardService;//拒绝卡号交易
    @Resource(name = "transOrderService")
    protected TransOrderService<TransOrder, Long> transOrderService;
    @Resource(name = "accountManageQ4Service")
    protected AccountManageQ4Service<BasePojo, Long> accountManageQ4Service;
    @Resource(name = "qian4SendLogService")
    protected Qian4SendLogService<Qian4SendLog, Long> qian4SendLogService;//发送日志
    @Resource(name = "bankService")
    protected BankService<Bank,Long> bankService;
    @Resource(name="ds_XYScanCodePayService")
    public XYScanCodePayService ds_XYScanCodePayService;
    @Resource(name="ds_JQScanCodePayService")
    public JQScanCodePayService ds_JQScanCodePayService;

    @Resource(name = "transPriorSettleService")
    private TransPriorSettleService<TransPriorSettle, Long> transPriorSettleService;

    @Resource(name = "cashMoneyService")
    private CashMoneyService<TransOrder, Long> cashMoneyService;
    @Resource(name = "userMoneyService")
    private UserMoneyService<UserMoney, Long> userMoneyService;
    
    static double CashMoneyFee = Double.parseDouble(ConConfig.getAttribute("CASH_MONEY_FEE"));
    /**
     * 消费
     * @return
     * @throws Exception
     */
    public String receivablesToCard() throws Exception {
        log.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        log.debug("XXXXXXXXXXXXXXXXXXXXXXXXX  扫码支付  收款  开始  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        log.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("totalFee"))
            totalFee = js.getString("totalFee");

        roleId = Long.parseLong(getJsonString("roleId"));
        //查询用户
        User user = userService.getUserById(userId);

        try {
            double money = Double.parseDouble(totalFee) / 100;
            Map<String, Object> map = userTransLimitService.transCheck(userId, roleId, null, money, 9L, SCANCODEPAY_FUNCKEY, null);
            if (map != null) {
                sendAppErrorMsg(map.get("code").toString(), map.get("value").toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //支付  接口
        payOrder(user, roleId);
        return null;
    }

    /**
     * 支付
     * @return
     * @throws Exception
     */
    public String payOrder(User user, long roleId) throws Exception {
        functionKey = SCANCODEPAY_FUNCKEY;
        Qian4SendLog send = null;//发送数据
        TransPriorSettle transPriorSettle = null;
        TransOrder transOrder = null;
        ScanCodePayParam scanCodePayParam = null;
        Map<String, Object> result = null;
        try {
            if (!checkPIV(functionKey)) {
                log.warn("扫码支付时, 银行接口暂停使用！");
                return null;
            }
            if (null != user) {
                Object[] resultA = assembleBean(user);
                if (null == resultA) return null;

                send = (Qian4SendLog) resultA[0];
                transOrder = (TransOrder) resultA[1];
                scanCodePayParam = (ScanCodePayParam) resultA[2];

                Tchannel tc = tchannelService.searchMobileTchannelByCode(user.getChannelId().intValue());

                send.setCollectionType(tc.getCode());
                send.setRoleId(roleId);
                double fee = calculateFee(user, transOrder.getRoleId(), transOrder.getTransMoney(), transOrder.getFeeRate());
                transOrder.setFeeMoney(fee);
                transOrder.setChargeAmount(transOrder.getTransMoney() - fee);
                transOrder.setOrderTypeId(RECEIVABLES);
                //下订单
                transPriorSettle = accountManageQ4Service.advanceOrder(transOrder, send, send.getCollectionType());
                PurchaseResult rs = null;
                switch (send.getCollectionType()){
                    case ScanCodePayBaseAction.TC_XY:
                        send.setMerchantId(XYScanCodePayServiceImpl.mchId);
                        rs = ds_XYScanCodePayService.purchase(send,scanCodePayParam,signaturePath);
                    case ScanCodePayBaseAction.TC_JQ:
                        rs = ds_JQScanCodePayService.getQRCode(send,scanCodePayParam,signaturePath);
                }

                //需要等待回调通知交易结果
                if(send.getCollectionType() == ScanCodePayBaseAction.TC_JQ){
                    result = new HashMap<>();
                    result.put("payUrl", rs.getPayUrl());
                    result.put("reqCode", rs.getReqCode());
                    result.put("reqMsg", rs.getReqMsg());

                    //保留二维码地址备查
                    transPriorSettle.setRequestParam(rs.getPayUrl());

                    if(!rs.getReqCode().equals("0000")){
                        //获取支付路径失败则直接标记交易失败
                        result = purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
                    }else {
                        transPriorSettle.setResponseCode("0002");
                        transPriorSettle.setBankMessage("订单创建成功,等待用户付款!");
                        transPriorSettleService.updateEntity(transPriorSettle);
                    }
                }else {
                    //解析结果
                    result = purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
                    log.debug("解析结果:{}",result);
                }
                sendAppMsg(result);
            } else {
                log.warn("我要收款时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //TODO:异常处理  超时处理
            revocationOrderTimeOut(send, transPriorSettle,scanCodePayParam);
            throw e;
        } finally {
            send = null;
            transPriorSettle = null;
            transOrder = null;
            result = null;
        }
        return null;
    }

    /**
     * 计算手续费
     *
     * @param user
     * @param roleId
     * @param transMoney
     * @param feeRate
     * @return
     */
    private Double calculateFee(User user, Long roleId, Double transMoney, Double feeRate) {
        double fee = NumberUtil.roundF2(feeRate * transMoney);
        if (3 == roleId.intValue()) {//封顶版
            if (fee > user.getFdMaxFee())
                fee = user.getFdMaxFee();
            else if (fee < user.getFdMinFee())
                fee = user.getFdMinFee();
        }
        return fee;
    }

//    /**
//     * 进钱扫码支付回调接口
//     * proOneMobile/scanPay/scanPayNL_JQNotify.action?code=0&message=su&externalId=
//     * @return
//     */
//    public String JQNotify(){
//        log.info("XXXXXXXXXXXXXXXXXXXXXXXXX  进钱交易结果通知接口  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
//        try {
//        	if(ConConfig.isFormal()){
//        		String param = (String)getRequest().getParameterNames().nextElement();
//                log.info("【进钱-回调 请求参数】:" + param);
//                if(StringUtils.isNotBlank(param)){
//                    JSONObject js = JSONObject.fromObject(param);
//                    String code = js.getString("code");//响应码
//                    String message = js.getString("message");//响应码对应信息
//                    String externalId = js.getString("externalId");//收款订单号
//
//                    TransOrder transOrder = transOrderService.searchOrderByOrderNum(externalId);
//                    if(1 == transOrder.getStatus()){
//                        log.info("【进钱-回调】: 订单号 " + externalId + "交易成功,已收到回调!");
//                        return null;
//                    }
//
//                    TransPriorSettle transPriorSettle = new TransPriorSettle();
//                    transPriorSettle.setOrderNum(externalId);
//                    transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
//
//                    Long sendId = transPriorSettle.getSendId();
//                    Qian4SendLog send = new Qian4SendLog();
//                    send.setId(sendId);
//                    send = qian4SendLogService.searchEntity(send);
//
//                    User user = userService.getUserById(transOrder.getUserId());
//
//                    Tchannel tc = new Tchannel();
//                    tc.setCode(transPriorSettle.getCollectionType());
//                    tc = tchannelService.searchEntity(tc);
//
//                    PurchaseResult rs = new PurchaseResult();
//                    if(code.equals("0")){
//                        rs.setReqCode("0000");
//                        rs.setReqMsg("交易成功!");
//                        rs.setStatus(1);
//
//                        //交易成功响应一个0即可
//                        HttpServletResponse res = getResponse();
//                        res.setCharacterEncoding("UTF-8");
//                        res.setContentType("text/json");
//                        res.getWriter().print("0");
//
//                    }else {
//                        rs.setReqCode(code);
//                        rs.setReqMsg(message);
//                        rs.setStatus(0);
//                    }
//                    purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
//                }
//        	}else{
//
//                String code = getRequest().getParameter("code");//响应码
//                String message = getRequest().getParameter("message");//响应码对应信息
//                String externalId = getRequest().getParameter("externalId");//订单号
//
//                TransOrder transOrder = transOrderService.searchOrderByOrderNum(externalId);
//
//                TransPriorSettle transPriorSettle = new TransPriorSettle();
//                transPriorSettle.setOrderNum(externalId);
//                transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
//
//                Long sendId = transPriorSettle.getSendId();
//                Qian4SendLog send = new Qian4SendLog();
//                send.setId(sendId);
//                send = qian4SendLogService.searchEntity(send);
//
//                User user = userService.getUserById(transOrder.getUserId());
//
//                Tchannel tc = new Tchannel();
//                tc.setCode(transPriorSettle.getCollectionType());
//                tc = tchannelService.searchEntity(tc);
//
//                PurchaseResult rs = new PurchaseResult();
//                if(code.equals("0")){
//                    rs.setReqCode("0000");
//                    rs.setReqMsg("交易成功!");
//                    rs.setStatus(1);
//
//                    //交易成功响应一个0即可
//                    HttpServletResponse res = getResponse();
//                    res.setCharacterEncoding("UTF-8");
//                    res.setContentType("text/json");
//                    res.getWriter().print("0");
//
//                }else {
//                    rs.setReqCode(code);
//                    rs.setReqMsg(message);
//                    rs.setStatus(0);
//                }
//                purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
//
//        	}
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;
//    }
    
    /**
     * 微信通知接口
     * http://localhost:8080/proOneMobile/scanPay/scanPayNL_WeixinNotify.action
     * <xml><appid><![CDATA[wx681256660695b62f]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><device_info><![CDATA[WEB]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1384671002]]></mch_id><nonce_str><![CDATA[wcjb4vptnkhdq4q4tpzqqpjm8al14s2k]]></nonce_str><openid><![CDATA[o8j3awFhMRtks46CSr-zLhrrHDYs]]></openid><out_trade_no><![CDATA[2016091421282100000843108213]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[A0095F46B6E1174E1A815AA4D93795A5]]></sign><time_end><![CDATA[20160914212834]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4006082001201609143964486731]]></transaction_id></xml>
     * @return
     * @throws IOException
     */
	public String WeixinNotify() throws IOException {

		ServletInputStream is = getRequest().getInputStream();
		ByteArrayOutputStream os = new ByteArrayOutputStream();

		BufferedReader r = new BufferedReader(new InputStreamReader(is));

		String line = null;

		StringBuffer sb = new StringBuffer();

		while ((line = r.readLine()) != null) {
			sb.append(line);
		}
		String data = new String(sb);
		log.info("接收到微信交易结果通知："+data);
		try {
			Map<String, Object> resultMap = XMLParser.getMapFromXML(data);
			// {transaction_id=4006082001201609143965196827,
			// nonce_str=i3nwqqd46ovwacdr9fl9irw452dayftj, bank_type=CFT,
			// openid=o8j3awFhMRtks46CSr-zLhrrHDYs,
			// sign=592B88F616CD7CEEE449BA3986E7B6B9, fee_type=CNY,
			// mch_id=1384671002, cash_fee=1, device_info=WEB,
			// out_trade_no=2016091421435800000843100200,
			// appid=wx681256660695b62f, total_fee=1, trade_type=JSAPI,
			// result_code=SUCCESS, time_end=20160914214414, is_subscribe=Y,
			// return_code=SUCCESS}
			String return_code = String.valueOf(resultMap.get("return_code"));// 响应码
			String return_msg = String.valueOf(resultMap.get("return_msg"));// 响应码
			
			PurchaseResult rs = new PurchaseResult();
			if (return_code.equals("SUCCESS")) {
				
				String out_trade_no = String.valueOf(resultMap.get("out_trade_no"));// 订单号
				String result_code = String.valueOf(resultMap.get("result_code"));// 订单号
				TransPriorSettle transPriorSettle = new TransPriorSettle();
				transPriorSettle.setOrderNum(out_trade_no);
				transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
				String orderNum = transPriorSettle.getOrderNum();
				
				TransOrder transOrder = transOrderService.searchOrderByOrderNum(orderNum);
				Long sendId = transPriorSettle.getSendId();
				Qian4SendLog send = new Qian4SendLog();
				send.setId(sendId);
				send = qian4SendLogService.searchEntity(send);
				User user = userService.getUserById(transOrder.getUserId());
				Tchannel tc = new Tchannel();
				tc.setCode(transPriorSettle.getCollectionType());
				tc = tchannelService.searchEntity(tc);
				
				Integer statWeixin = 0; 
				
				if(result_code.equals("SUCCESS")){
					rs.setReqCode("0000");
					rs.setReqMsg("交易成功!");
					rs.setStatus(1);
					statWeixin=1;
				}else{
					String err_code = String.valueOf(resultMap.get("err_code"));// 订单号
					String err_code_des = String.valueOf(resultMap.get("err_code_des"));// 订单号
					rs.setReqCode(err_code);
					rs.setReqMsg(err_code_des);
					rs.setStatus(0);
					statWeixin=0;
				}
				if(transOrder.getStatus() == 3){//未付款 去更新状态
					purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
				}else if (!transOrder.getStatus().equals(statWeixin)){//如果订单状态不一致时，更新状态
					purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
				}//判断是否已经通知交易结果
				
				// 交易成功响应一个0即可
				StringBuffer sb1 = new StringBuffer();
				sb1.append("<xml>");
				sb1.append("<return_code><![CDATA[SUCCESS]]></return_code>");
				sb1.append("<return_msg><![CDATA[OK]]></return_msg>");
				sb1.append("</xml>");

				HttpServletResponse res = getResponse();
				res.setCharacterEncoding("UTF-8");
				res.setContentType("text/xml");
				res.getWriter().print(sb.toString());

			}else{
				log.error("微信接口通知异常："+resultMap);
			}
			
		} catch (Exception e) {
			log.error("接收微信通知接口异常："+ e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 商联储通知接口
	 * http://localhost:8080/proOneMobile/scanPay/scanPayNL_SlcNotify.action?orgSendSeqId=
	 * <xml><appid><![CDATA[wx681256660695b62f]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><device_info><![CDATA[WEB]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1384671002]]></mch_id><nonce_str><![CDATA[wcjb4vptnkhdq4q4tpzqqpjm8al14s2k]]></nonce_str><openid><![CDATA[o8j3awFhMRtks46CSr-zLhrrHDYs]]></openid><out_trade_no><![CDATA[2016091421282100000843108213]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[A0095F46B6E1174E1A815AA4D93795A5]]></sign><time_end><![CDATA[20160914212834]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4006082001201609143964486731]]></transaction_id></xml>
	 * @return
	 * @throws IOException
	 */
	public String SlcNotify() throws IOException {
		
		
	
		//{"fee":"1","mac":"d9fcf9fb3a6104e52267509780300b56","orgSendSeqId":"183719039","organizationId":"slcceshi4","payDesc":"支付成功","payResult":"00","transAmt":"10"}
		try {
			
			String data = getRequest().getParameter("data");
			if(StringUtils.isBlank(data)){//{"fee":"1","mac":"20d42d49638f976507552e9825b4b8e0","orgSendSeqId":"3108266","organizationId":"slcceshi4","payDesc":"支付成功","payResult":"00","transAmt":"10"}
				//data = "{\"fee\":\"1\",\"mac\":\"20d42d49638f976507552e9825b4b8e0\",\"orgSendSeqId\":\"3108276\",\"organizationId\":\"slcceshi4\",\"payDesc\":\"支付成功\",\"payResult\":\"00\",\"transAmt\":\"10\"}";
				String orgSendSeqId = getRequest().getParameter("orgSendSeqId");
				data = "{\"fee\":\"1\",\"mac\":\"20d42d49638f976507552e9825b4b8e0\",\"orgSendSeqId\":\""+orgSendSeqId+"\",\"organizationId\":\"slcceshi4\",\"payDesc\":\"支付成功\",\"payResult\":\"00\",\"transAmt\":\"10\"}";
			}
			log.info("接收到商联储交易结果通知：{}",data);
			Map<String, String> resultMap = JSONUtil.parseToBean(data);
			String orgSendSeqId = resultMap.get("orgSendSeqId");
			String payResult = resultMap.get("payResult");
			String payDesc = resultMap.get("payDesc");

            TransPriorSettle transPriorSettle = new TransPriorSettle();
            transPriorSettle.setOrderNum(orgSendSeqId);
            transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
            String orderNum = transPriorSettle.getOrderNum();
            TransOrder transOrder = transOrderService.searchOrderByOrderNum(orderNum);
            Long sendId = transPriorSettle.getSendId();
            Qian4SendLog send = new Qian4SendLog();
            send.setId(sendId);
            send = qian4SendLogService.searchEntity(send);
            User user = userService.getUserById(transOrder.getUserId());
            Tchannel tc = new Tchannel();
            tc.setCode(transPriorSettle.getCollectionType());
            tc = tchannelService.searchEntity(tc);
            Integer stat = 0; 
            PurchaseResult rs = new PurchaseResult();
            if(payResult.equals("00")){
                rs.setReqCode("0000");
                rs.setReqMsg("交易成功!");
                rs.setStatus(1);
                stat = 1;
                
            }else {
                rs.setReqCode(payResult);
                rs.setReqMsg(payDesc);
                rs.setStatus(0);
                stat = 0;
            }
            
            if(transOrder.getStatus() == 3){//未付款 去更新状态
				purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
			}else if (!transOrder.getStatus().equals(stat)){//如果订单状态不一致时，更新状态
				purchaseResolveResult(send, rs, transOrder, transPriorSettle, user, tc);
			}//判断是否已经通知交易结果
            if(payResult.equals("00")){
            	double transMoney = transOrder.getTransMoney();
            	Double chargeAmount = transOrder.getChargeAmount();

            	double cashMoneyFee = CashMoneyFee + NumberUtil.roundF2(transMoney * user.getCashRate());//提现手续费
                
                double cashMoney = chargeAmount-cashMoneyFee;
                
            	cashMoney(user, orderNum, cashMoney, cashMoneyFee);
            }
            //交易成功响应一个true即可
        	OutputStream os = getResponse().getOutputStream();
 			os.write("true".getBytes("UTF-8"));
 			os.flush();
 			os.close();

		} catch (Exception e) {
			log.error("接收通知接口异常：{}", e.getMessage());
			e.printStackTrace();
		}
//		HttpServletResponse res = getResponse();
//		res.setCharacterEncoding("UTF-8");
//		res.setContentType("text/json");
//		res.getWriter().print("true");
		return null;
	}

	private String cashMoney(User user, String orderNum, Double cashMoney,Double cashMoneyFee ) {
		userId = user.getUserId();
		functionKey = "CASHMONEY";
		log.debug("functionKey = " + functionKey);
		log.debug("userId = " + userId);
		log.debug("cashMoney = " + cashMoney);
		log.debug("cashMoneyFee = " + cashMoneyFee);
		log.debug("orderNum = " + orderNum);
		
		// 查询订单
		TransOrder order = new TransOrder();
		
		try {
			Date date = new Date();
			order.setOrderNum(orderNum);
			order = transOrderService.searchEntity(order);
			TransPriorSettle transPriorSettle = new TransPriorSettle();
			transPriorSettle.setOrderNum(orderNum);
			transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
			// 判断 绑定银行卡
			if (null == user.getBankStatus() || 3 == user.getBankStatus()) {
				sendWeChatErrorMsg("6041");
				return null;
			} else if (2 == user.getBankStatus()) {
				sendWeChatErrorMsg("6042");
				return null;
			} else if (0 == user.getBankStatus()) {// 0:认证失败 1:认证通过 2:审核中
													// 3:未申请认证 DEFAULT 3
				sendWeChatErrorMsg("6043");
				return null;
			}

			// 判断用户 结算状态
			if (user.getClearStatus() == null || user.getClearStatus().intValue() != 1) {
				String message = "用户存在违法，请跟管理员联系！";
				sendWeChatErrorMsg(message);
				return null;
			}

			// 查询订单
			order.setOrderNum(orderNum);
			order = transOrderService.searchEntity(order);
			transPriorSettle = new TransPriorSettle();
			transPriorSettle.setOrderNum(orderNum);
			transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
			if (null == order) {
				log.warn("安全提现时, 不存在该订单！");
				sendWeChatErrorMsg("6086");
				return null;
			}
			if (1 != order.getOrderTypeId().intValue()) {// 订单不是收款订单
				log.warn("安全提现时, 订单不是收款订单！");
				sendWeChatErrorMsg("6087");
				return null;
			}
			if (1 != order.getStatus().intValue()) {// 收款订单不是交易成功的订单
				log.warn("提现失败，收款订单不是交易成功的订单！");
				sendWeChatErrorMsg("6092");
				return null;
			}

			double chargeAmount = order.getChargeAmount();
			 if (chargeAmount != NumberUtil.roundF2((cashMoneyFee + cashMoney)) && chargeAmount != cashMoney) {//金额不相等
			 log.warn("安全提现时, 传入提现金额与手续费不符！");
			 return null;
			 }

			if (null != order.getCashOrderNum()) {
				TransOrder cashOrder = new TransOrder();
				cashOrder.setOrderNum(order.getCashOrderNum());
				cashOrder = transOrderService.searchEntity(cashOrder);
				if (null == cashOrder || cashOrder.getStatus().intValue() != 0) {

					return null;
				}
			}
			// 金额是否足够
			boolean isZhugou = userMoneyService.moneyTheAdequacy(userId, chargeAmount, 1);
			if (!isZhugou) {
				log.info("提现错误，金额不足！");
				sendWeChatErrorMsg("6082", chargeAmount + "");
				return null;
			}

			TransOrder transOrder = new TransOrder();
			transOrder.setOrderNum(getOrderNumByDate(date));
			transOrder.setOrderTypeId(OrderTypeUtil.AUTO_CASH_MONEY);// 自动提现
			transOrder.setUserId(userId);
			transOrder.setTransMoney(chargeAmount);

			transOrder.setFeeMoney(cashMoneyFee);// fee);//手续费
			transOrder.setBrokerage(0.0000);// brokerage);
			transOrder.setDealerBrokerage(0.0000);
			transOrder.setChargeAmount(cashMoney);
			transOrder.setRootCategory("账务管理");
			transOrder.setCategory("提现");
			transOrder.setObjectiveName(user.getCardholder());// 对方姓名
			transOrder.setObjectiveCard(user.getBankCard());// 对方银行卡
			transOrder.setObjectiveOpBank(user.getOpeningBank());// 对方银行

			transOrder.setStatus(2);
			transOrder.setClearing(0);// 结算状态 0未结算 1结算
			transOrder.setDescription("系统结算");// 交易详情
			transOrder.setCreateDate(date);
			transOrder.setUpdateLongTime(date.getTime());

			transOrder.setObjectiveBBank(user.getBranchesBank());// 对方。银行支行
			transOrder.setObjectiveBBProvince(user.getBBankProvince());
			transOrder.setObjectiveBBCity(user.getBBankCity());
			transOrder.setObjectiveMobile(user.getMobile());// 对方手机号
			transOrder.setObjectiveBBankCode(user.getBranchesBankCode());
			transOrder.setObjectiveAccBankCode(user.getAccBankCode());
			transOrder.setTerminalTypeId(user.getTerminalTypeId());
			transOrder.setRoleId(2l);
			transOrder.setOrgOrderNum(order.getOrderNum());// 原订单编号
			transOrder.setFeeRate(user.getCashRate());// 订单费率
			transOrder.setFdMaxFee(0.00);// 用户封顶最高
			transOrder.setFdMinFee(2.00);// 用户封顶最低
			transOrder.setClientType(1);

			// 修改原订单
			transOrderService.updateCashOrderByNum(order.getOrderNum(), transOrder.getOrderNum());

			// 判断 机构预存款
			int flag = cashMoneyService.weChartCashMoneySafe(transOrder);

		    if (flag == 2) {// 预存款不足
				// 修改原订单
				transOrderService.updateCashOrderByNum(order.getOrderNum(), "");
			}
		} catch (Exception e) {
			// 修改原订单
			//transOrderService.updateCashOrderByNum(order.getOrderNum(), "");
			e.printStackTrace();
		}
		return null;
	}

}
